import copy
import threading
import time

import streamlit as st
import pymysql
import random
import datetime

from tags import tags

MYSQL_HOST = "127.0.0.1"
MYSQL_PORT = 3306
MYSQL_USER = "root"
MYSQL_PASSWORD = "G5v3m5e5!"
MYSQL_DB = "random_tag_ygo"

REROLL = 1

st.set_page_config(
    page_title="厄厄杯-线上娱乐赛",
    page_icon="👋",
)

hide_streamlit_style = """
    <style>
        .reportview-container {
            margin-top: -2em;
        }
        #MainMenu {visibility: hidden;}
        .stDeployButton {display:none;}
        footer {visibility: hidden;}
        #stDecoration {display:none;}
    </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)

# 连接MySQL数据库
conn = pymysql.connect(
    host=MYSQL_HOST,
    port=MYSQL_PORT,
    user=MYSQL_USER,
    password=MYSQL_PASSWORD,
    database=MYSQL_DB
)

# 创建游标
cursor = conn.cursor()

# 创建user_data表（如果不存在）
cursor.execute("""
    CREATE TABLE IF NOT EXISTS reroll (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(255) UNIQUE,
        times INT DEFAULT 0,
        created_at DATE DEFAULT (CURRENT_DATE)
    )
""")

# Streamlit应用程序
st.markdown("<h1 style='text-align: center;'>🎉厄厄杯-线上娱乐赛🎉</h1>", unsafe_allow_html=True)

# 设定目标日期
target_date = datetime.datetime(2024, 2, 5,13,0)

now = datetime.datetime.now()
countdown = target_date - now

# 格式化显示倒计时
days = countdown.days
hours, remainder = divmod(countdown.seconds, 3600)
minutes, seconds = divmod(remainder, 60)

# 创建一个自定义的HTML和CSS样式
badge_html = """
<div style="
    border: 3px solid #B8860B; 
    border-radius: 15px; 
    text-align: center; 
    color: #B8860B; 
    font-size: 24px; 
    padding: 5px; 
    width: 200px;
    margin: auto;">
    测试阶段
</div>
"""

# 在Streamlit应用中显示它
st.markdown(badge_html, unsafe_allow_html=True)

# 使用Markdown和HTML创建简约的倒计时显示
st.markdown(
    f"<h4 style='text-align: center;'>⏱ 距离比赛还有 : {days} 天 {hours} 小时</h2>",
    unsafe_allow_html=True)


st.markdown("**最后机会！**你有最后一次重新抽取**某一个**字段的机会！**但是**，没人能保证你抽到的字段是更好还是更坏！")

# 输入框和按钮
username = st.text_input("请输入比赛昵称:")
verify = st.text_input("请输入验证码:")

button1 = st.button("查询")

st.session_state.times = 0

def reroll_single(reroll_name):
    if st.session_state.times >= REROLL:
        st.error("已经没有重新抽取的机会了！")
    cursor.execute("SELECT times FROM reroll WHERE username=%s", (username,))
    reroll_info = cursor.fetchone()
    st.session_state.times = int(reroll_info[0])
    cursor.execute("SELECT * FROM random_tags WHERE username=%s", (username,))
    existing_data = cursor.fetchone()
    elements = str(existing_data[2]).replace(" ", "").split(',')
    rem = reroll_name
    while rem in elements:
        rem = random.choice(tags)
    new_es = []
    change = False
    for i in elements:
        if i != reroll_name:
            new_es.append(i)
        else:
            change = True
            new_es.append(rem)
    if not change:
        print("无事发生")
    print("before",st.session_state.times)
    st.session_state.times += 1
    print("after",st.session_state.times)
    cursor.execute("UPDATE reroll SET times = %s WHERE username = %s",
                   (int(st.session_state.times), username))
    conn.commit()
    elements_str = ', '.join(new_es)
    cursor.execute("UPDATE random_tags SET elements = %s WHERE username = %s",
                   (elements_str, username))
    conn.commit()
    st.success("重新抽取成功！请重新查询！")
    st.session_state.stage = 0
    time.sleep(2)
    st.rerun()


if 'stage' not in st.session_state:
    st.session_state.stage = 0


if button1:
    # 查询数据库
    if not username or username == "":
        st.error(f"用户名不能为空")
    else:
        cursor.execute("SELECT * FROM random_tags WHERE username=%s", (username,))
        existing_data = cursor.fetchone()
        if existing_data:
            code = existing_data[3]
            if code == verify:
                elements = str(existing_data[2]).replace(" ","").split(',')
                st.markdown(f"选手：**{username}** ")
                print(elements)
                cursor.execute("SELECT times FROM reroll WHERE username=%s", (username,))
                reroll_info = cursor.fetchone()
                if reroll_info:
                    st.session_state.times = int(reroll_info[0])
                    print("查询后 ",st.session_state.times)
                else:
                    cursor.execute("INSERT INTO reroll (username) VALUES (%s)",
                                   (username))
                    conn.commit()
                    st.session_state.times = 0

                local_reroll = copy.deepcopy(REROLL)
                print("before_reroll",st.session_state.times)
                if "金傲大奖赛" in elements:
                    local_reroll += 1
                    st.markdown("**因为你抽中了金傲大奖赛，所以获得了一次额外的重抽的机会！要珍惜哦！**")
                if "无限起动" in elements:
                    local_reroll += 1
                    st.markdown("**因为你抽中了无限起动，所以获得了一次额外的重抽的机会！要珍惜哦！**")
                if "骑甲虫" in elements:
                    local_reroll += 1
                    st.markdown("**因为你抽中了骑甲虫，所以获得了一次额外的重抽的机会！要珍惜哦！**")
                if "齿轮" in elements:
                    local_reroll += 1
                    st.markdown("**因为你抽中了齿轮，所以获得了一次额外的重抽的机会！要珍惜哦！**")
                REROLL = local_reroll
                print(REROLL)

                st.session_state.stage = 1
                st.session_state.elements = elements

            else:
                st.error(f"选手 **{username}** 验证码不正确！")
        else:
            st.error(f"选手 **{username}** 不存在！")

if st.session_state.stage == 1:
    st.markdown(f"你还有 **{max(0,REROLL-st.session_state.times)}** 次重新选择某一个字段的机会")
    st.markdown(f"已抽选的字段是：")
    # 创建两列布局
    pic1 ,pic2, pic3 = st.columns(3)
    # 在第一列显示图片
    re1=False
    re2=False
    re3=False
    with pic1:
        st.image(f"img/card/cut_{st.session_state.elements[0]}.jpg", use_column_width= "auto" ,caption=st.session_state.elements[0])
        if st.session_state.times< REROLL or st.session_state.stage == 2:
            re1 = st.button("重抽！",key='re1')
    # 在第一列显示图片
    with pic2:
        st.image(f"img/card/cut_{st.session_state.elements[1]}.jpg", use_column_width= "auto",caption=st.session_state.elements[1])
        if st.session_state.times < REROLL or st.session_state.stage == 2:
            re2 = st.button("重抽！",key='re2')
    # 在第一列显示图片
    with pic3:
        st.image(f"img/card/cut_{st.session_state.elements[2]}.jpg", use_column_width= "auto",caption=st.session_state.elements[2])
        if st.session_state.times < REROLL or st.session_state.stage == 2:
            re3 = st.button("重抽！",key='re3')
    if re1:
        reroll_single(st.session_state.elements[0])
        # st.rerun()
    if re2:
        reroll_single(st.session_state.elements[1])
        # st.rerun()
    if re3:
        reroll_single(st.session_state.elements[2])
        # st.rerun()

# 关闭数据库连接
cursor.close()
conn.close()
